#!/usr/bin/perl
use strict;
use warnings;

use File::Glob ':glob';
use FileHandle;
use Fcntl ':flock';    # import LOCK_* constants

use Contact;
use Contact::Manager;

my $debug = 1;

my @failed_queue = bsd_glob('/home/woeishya/domains/ocfaustralia.org/connect/public_html/cgi-bin/mailqueue/*.timedout');

my $email_counter  = {};
my $email_file_map = {};

foreach my $cur_file (@failed_queue) {
    my $cur_email = processMailQueueFile($cur_file);
    if ($cur_email) {
        $email_counter->{$cur_email} = ( ( defined( $email_counter->{$cur_email} ) && $email_counter->{$cur_email} =~ /\d+/ ) ? $email_counter->{$cur_email} + 1 : 1 );
        $email_file_map->{$cur_email}
            = ( defined( $email_file_map->{$cur_email} ) && ref( $email_file_map->{$cur_email} ) && ref( $email_file_map->{$cur_email} ) eq 'ARRAY' ) ? $email_file_map->{$cur_email} : [];
        push @{ $email_file_map->{$cur_email} }, $cur_file;
    } ## end if ($cur_email)
} ## end foreach my $cur_file (@failed_queue)

use Data::Dumper;
print Data::Dumper::Dumper($email_counter);

foreach my $cur_email ( keys( %{$email_counter} ) ) { 
    if ( $email_counter->{$cur_email} >= 2 ) {
        warn "Errors for $cur_email exceed threshold" if $debug;
        my $contacts = Contact::Manager->get_contacts( query => [ email => $cur_email ] );
        foreach my $contact ( @{$contacts} ) {
            warn "Deactivating contact id " . $contact->id() if $debug;
            $contact->active(0);
            $contact->save();
        }
        if ( scalar( @{$contacts} ) ) {
            foreach my $failed_file ( @{ $email_file_map->{$cur_email} } ) {
                if ( !unlink $failed_file ) {
                    warn "Failed to remove $failed_file" if $debug;
                }
            }
        }
    } ## end if ( $email_counter->{$cur_email} > 2 )
} ## end foreach my $cur_email ( keys( %{$email_counter}...

sub processMailQueueFile {
    my $filename = shift;
    warn "Opening $filename" if $debug;
    my $fh = new FileHandle $filename, "r";
    if ( $fh && flock( $fh, LOCK_EX | LOCK_NB ) ) {
        warn "Exclusive lock on file obtained" if $debug;
        my $line = $fh->getline;
        chomp($line);
        $fh->close();
        return $line;
    } ## end if ( $fh && flock( $fh, LOCK_EX | LOCK_NB ...
} ## end sub processMailQueueFile
